const app = getApp()

Page({

  /**
   * 页面的初始数据
   */
  data: {
    currentPIndex:0,
    currentWIndex:0,
    currentData:[],
    currentWorkerData:[],
    customeFlag:false,
    workerFlag:false,
    id:'',
    states: [{
      id: 1,
      name: '进行中',
    }, {
      id: 2,
      name: '已完成'
    }, {
      id: 3,
      name: '已回款'
    }, {
      id: 4,
      name: '已发工资'
    }],
    customerList: [],
    workerList: [],
    unitList: [],
    processList: [],
    orderId:'',
    orderName: '',
    customerIndex: 0,
    customerId: '',
    customerName: '',
    state:1,
    remark: '',
    processArry:[
      {
        processIndex: '',
        processId: '',
        processName: '',
        unitIndex: '',
        unitId:'',
        unitName:'',
        customerprice:'',
        workers:[
          {
            workerIndex: '',
            workerId:'',
            workerName:'',
            workerprice:'',
            number:'',
          }
        ],
      }
  ],
    userNameRules: [
      { required: true, message: '请输入客户名称', trigger: 'blur' },
      { min: 2, max: 10, message: '客户名称长度在2-10个字符之间', trigger: 'blur' },
    ],
    phoneRules:  [
      { required: true, message: '请输入账号码', trigger: 'blur' },
      { min: 11, max: 11, message: '账号码格式不正确', trigger: 'blur' }
    ],
    addressRules: [
      { required: true, message: '请输入地址', trigger: 'blur' },
      { min: 2, max: 50, message: '地址长度在2-50个字符之间', trigger: 'blur' },
    ],
    // passwordRules: [
    //   { required: true, message: '请输入登录密码', trigger: 'blur' },
    //   { min: 6, max: 20, message: '密码长度在6-20个字符之间', trigger: 'blur' }    ],
  },
  handleInputChange(e) {
    const searchTerm = e.detail.value; 
    const filteredItems = this.data.customerList.filter(item => 
        new RegExp(searchTerm, 'i').test(item.username) || new RegExp(searchTerm, 'i').test(item.phone)
    );
    this.setData({
      currentData:filteredItems
    })
},
handleInputChange2(e) {
  const searchTerm = e.detail.value; 
  const filteredItems = this.data.workerList.filter(item => 
      new RegExp(searchTerm, 'i').test(item.username) || new RegExp(searchTerm, 'i').test(item.phone)
  );
  this.setData({
    currentWorkerData:filteredItems
  })
},
  remarkInput(e){
    let value = e.detail.value;
    this.setData({
      remark:value
   })
  },
  orderNameInput(e){
    let value = e.detail.value;
    this.data.orderName=value
    this.setData({
      processArry:this.data.processArry
   })
  },
  customerpriceInput(e){
    let value = e.detail.value;
    let index = e.currentTarget.dataset.index;
    this.data.processArry[index].customerprice=value
    this.setData({
      processArry:this.data.processArry
   })
  },
  workerpriceInput(e){
    let value = e.detail.value;
    let index = e.currentTarget.dataset.index;
    let id = e.currentTarget.dataset.id;
    this.data.processArry[index].workers[id].workerprice=value
    this.setData({
      processArry:this.data.processArry
   })
  },
  numberInput(e){
    let value = e.detail.value;
    let index = e.currentTarget.dataset.index;
    let id = e.currentTarget.dataset.id;
    this.data.processArry[index].workers[id].number=value
    this.setData({
      processArry:this.data.processArry
   })
  },
  reset(){
    this.data.processArry=[
      {
        processIndex: '',
        processId: '',
        processName: '',
        unitIndex: '',
        unitId:'',
        unitName:'',
        customerprice:'',
        workers:[
          {
            workerIndex: '',
            workerId:'',
            workerName:'',
            workerprice:'',
            number:'',
          }
        ],
      }
  ]
       this.setData({
          orderId:'',
          orderName: '',
          customerIndex: 0,
          customerId: '',
          customerName: '',
          processArry:this.data.processArry
       })
 },
  addProcess(){
    this.data.processArry.push({
      processId:'',
      processName:'',
      unitId:'',
      unitName:'',
      customerprice:'',
      workers:[
        {
          workerId:'',
          workerName:'',
          workerprice:'',
          number:'',
          phone:'',
        }
      ],

    })
       this.setData({
          processArry:this.data.processArry
       })
 },
 delProcess(e){
  let index = e.currentTarget.dataset.index;
  console.log(index)
   this.data.processArry.splice(index, 1);
   console.log(999,this.data.processArry)

   this.setData({
    processArry:this.data.processArry
 })
 },
 addWorker(e){
  const index = e.currentTarget.dataset.index;
    this.data.processArry[index].workers.push({
             phone:'',
             workerId:'',
             workerName:'',
             workerprice:'',
             number:'',
           })
           this.setData({
            processArry:this.data.processArry
         })
         console.log(123,this.data.processArry[index].workers);
 },
 delWorker(e){
  const index = e.currentTarget.dataset.index;
  const id = e.currentTarget.dataset.id;
   this.data.processArry[index].workers.splice(id, 1);
   this.setData({
    processArry:this.data.processArry
 })
 },
 choseCustomer:function(){
   console.log(123);
   this.setData({
    currentData:this.data.customerList,
    customeFlag:true
   })
 },
 chose:function(e){
  const id = e.currentTarget.dataset.id;
  const name = e.currentTarget.dataset.type;
  this.setData({
   customeFlag:false,
   customerId: id,
   customerName: name
  })
},
 onClosePopup3:function(){
  console.log(123);
  this.setData({
   customeFlag:false
  })
},
  bindCustomerChange:function(e){
    console.log("：" + e.detail.value);
    //获取对象数组中的id值
    this.setData({
      customerIndex: e.detail.value,
      customerId: this.data.customerList[e.detail.value].id,
      customerName: this.data.customerList[e.detail.value].username
    });
  },
  onStateChange(e) {
    const {
      currentKey
    } = { ...e.detail
    };
    console.log(12343,currentKey);
    this.setData({
      state:currentKey
    });
  },
  bindProcessChange:function(e){
    const index = e.currentTarget.dataset.index;
    console.log("：" + e.detail.value);
    //获取对象数组中的id值
    this.data.processArry[index].processIndex=e.detail.value;
    this.data.processArry[index].processId=this.data.processList[e.detail.value].id,
    this.data.processArry[index].processName=this.data.processList[e.detail.value].name
    this.setData({
      processArry: this.data.processArry
    });
  },
  bindUnitChange:function(e){
    const index = e.currentTarget.dataset.index;
    console.log("：" + e.detail.value);
    //获取对象数组中的id值
    this.data.processArry[index].unitIndex=e.detail.value;
    this.data.processArry[index].unitId=this.data.unitList[e.detail.value].id,
    this.data.processArry[index].unitName=this.data.unitList[e.detail.value].name
    this.setData({
      processArry: this.data.processArry
    });
  },
  choseWorker:function(e){
    const index = e.currentTarget.dataset.index;
    const i = e.currentTarget.dataset.id;
    this.setData({
      currentPIndex:index,
      currentWIndex:i,
      currentWorkerData:this.data.workerList,
      workerFlag:true
    });
  },
  chose2:function(e){
    const phone = e.currentTarget.dataset.index;
    const id = e.currentTarget.dataset.id;
    const username = e.currentTarget.dataset.type;
    const index = this.data.currentPIndex;
    const i = this.data.currentWIndex;
    this.data.processArry[index].workers[i].workerId=id,
    this.data.processArry[index].workers[i].workerName=username
    this.data.processArry[index].workers[i].phone=phone
   this.setData({
    processArry: this.data.processArry,
    workerFlag:false
   })
 },
  onClosePopup2:function(){
   console.log(123);
   this.setData({
    workerFlag:false
   })
 },
  bindWorkerChange:function(e){
    const index = e.currentTarget.dataset.index;
    const id = e.currentTarget.dataset.id;
    console.log("：" + e.detail.value);
    //获取对象数组中的id值
    this.data.processArry[index].workers[id].workerIndex=e.detail.value;
    this.data.processArry[index].workers[id].workerId=this.data.workerList[e.detail.value].id,
    this.data.processArry[index].workers[id].workerName=this.data.workerList[e.detail.value].username
    this.data.processArry[index].workers[id].phone=this.data.workerList[e.detail.value].phone
    this.setData({
      processArry: this.data.processArry
    });
  },
  async submit() {
    if(!this.data.orderName){
      wx.showToast({
        title: '请填写订单名称',
        icon: 'none'
      });
      return
    }
    if(!this.data.customerName){
      wx.showToast({
        title: '请选择客户',
        icon: 'none'
      });
      return
    }
    if(!this.data.state){
      wx.showToast({
        title: '请选择订单状态',
        icon: 'none'
      });
      return
    }
    console.log(this.validateOrderData(this.data.processArry));
    const valid=this.validateOrderData(this.data.processArry);
    if(valid.priceFlag!=0){
      if(valid.priceFlag==1){
        wx.showToast({
          title: '工人单价必须小于客户单价',
          icon: 'none'
        });
      }
      // if(valid.priceFlag==2){
      //   wx.showToast({
      //     title: '工人单价的五倍必须超过客户单价',
      //     icon: 'none'
      //   });
      // }
    }else if(!valid.isValid){
      wx.showToast({
        title: '请提交完整数据',
        icon: 'none'
      });
      
    }else{
      let url="/addOrder"
      let orderId='';
      console.log(19999,this.data.id);
      if(this.data.id!='' && this.data.id!=undefined && this.data.id!=null){
        url="/upOrder"
        orderId=this.data.orderId;
        console.log(orderId)
        // 保存原有工序和工人信息，用于智能匹配
        try {
          const originalProcesses = await this.wxRequest({
            url: app.globalData.onlineUrl+'/getProcessByProcessIds',
            method: 'POST',
            data: { orderId: orderId }
          });
          
          // 为每个原有工序获取其关联的工人信息
          this.originalProcessFullMap = {};
          for (const process of originalProcesses) {
            const workers = await this.wxRequest({
              url: app.globalData.onlineUrl+'/getWorkerByWorkerIds',
              method: 'POST',
              data: { orderProcessId: process.orderProcessId }
            });
            this.originalProcessFullMap[process.orderProcessId] = {
              processId: process.processId,
              orderProcessId: process.orderProcessId,
              workerIds: workers.map(w => w.workerId).sort()
            };
          }
          console.log('原有工序完整信息:', this.originalProcessFullMap);
        } catch (error) {
          console.error('获取原有工序失败:', error);
        }
      }else{
        orderId=this.getOrderNo("yyyyMMddhhmmssS")+Math.floor(Math.random() * 89) + 10;
      }
      try {
        const processIds = [];
        const processArray = this.data.processArry;
        
        // 智能匹配算法：根据processId和workerIds匹配原有工序
        const findMatchingOriginalProcess = (currentProcess) => {
          if (!this.originalProcessFullMap) return null;
          
          const currentWorkerIds = currentProcess.workers.map(w => w.workerId).sort();
          
          for (const [orderProcessId, originalProcess] of Object.entries(this.originalProcessFullMap)) {
            // 完全匹配：processId相同 AND workerIds完全相同
            if (originalProcess.processId === currentProcess.processId && 
                JSON.stringify(originalProcess.workerIds) === JSON.stringify(currentWorkerIds)) {
              return orderProcessId;
            }
          }
          
          // 部分匹配：只有processId相同
          for (const [orderProcessId, originalProcess] of Object.entries(this.originalProcessFullMap)) {
            if (originalProcess.processId === currentProcess.processId) {
              return orderProcessId;
            }
          }
          
          return null;
        };
        
        // 记录已使用的原有工序ID
        const usedOrderProcessIds = new Set();
        
        // 找出不再需要的工序并删除
        if (this.data.id && this.originalProcessFullMap) {
          const matchedOrderProcessIds = new Set();
          
          for (const p of processArray) {
            const matchedId = findMatchingOriginalProcess(p);
            if (matchedId) {
              matchedOrderProcessIds.add(matchedId);
            }
          }
          
          for (const orderProcessId of Object.keys(this.originalProcessFullMap)) {
            if (!matchedOrderProcessIds.has(orderProcessId)) {
              console.log('删除不再需要的工序:', orderProcessId);
              await this.wxRequest({
                url: app.globalData.onlineUrl+'/delOrderForProcess',
                method: 'POST',
                data: { orderId: orderId, orderProcessId: orderProcessId }
              });
            }
          }
        }
        
        // 处理每个工序
        for (const p of processArray) {
          let orderProcessId;
          let isNewProcess = false;
          
          const matchedOrderProcessId = this.data.id ? findMatchingOriginalProcess(p) : null;
          
          if (matchedOrderProcessId && !usedOrderProcessIds.has(matchedOrderProcessId)) {
            // 使用匹配的原有工序ID
            orderProcessId = matchedOrderProcessId;
            usedOrderProcessIds.add(orderProcessId);
            
            // 更新工序信息
            await this.wxRequest({
              url: app.globalData.onlineUrl+'/upOrderForProcess',
              method: 'POST',
              data: {
                orderProcessId: orderProcessId,
                processId: p.processId,
                processName: p.processName,
                unitId: p.unitId,
                unitName: p.unitName,
                customerprice: p.customerprice
              }
            });
          } else {
            // 生成新的工序ID
            orderProcessId = this.getOrderNo("yyyyMMddhhmmssS")+Math.floor(Math.random() * 89) + 10;
            isNewProcess = true;
            
            // 如果找到了匹配但已被使用，或者找到了匹配，需要迁移数据
            if (matchedOrderProcessId) {
              console.log('迁移工人数量记录:', matchedOrderProcessId, '->', orderProcessId);
              await this.wxRequest({
                url: app.globalData.onlineUrl+'/migrateWorkerNumberRecords',
                method: 'POST',
                data: {
                  oldOrderProcessId: matchedOrderProcessId,
                  newOrderProcessId: orderProcessId
                }
              });
            }
            
            // 新增工序
            await this.wxRequest({
              url: app.globalData.onlineUrl+'/addOrderForProcess',
              method: 'POST',
              data: {
                orderProcessId: orderProcessId,
                orderId: orderId,
                processId: p.processId,
                processName: p.processName,
                unitId: p.unitId,
                unitName: p.unitName,
                customerprice: p.customerprice
              }
            });
          }
          
          // 增量更新工人记录
          if(this.data.id && !isNewProcess) {
            // 获取原有工人列表
            const originalWorkers = await this.wxRequest({
              url: app.globalData.onlineUrl+'/getWorkerByWorkerIds',
              method: 'POST',
              data: { orderProcessId: orderProcessId }
            });
            
            const originalWorkerMap = {};
            originalWorkers.forEach(worker => {
              originalWorkerMap[worker.workerId] = worker;
            });
            
            const currentWorkerIds = p.workers.map(w => w.workerId.toString());
            const originalWorkerIds = Object.keys(originalWorkerMap);
            
            // 删除不再需要的工人
            for (const workerId of originalWorkerIds) {
              if (!currentWorkerIds.includes(workerId)) {
                await this.wxRequest({
                  url: app.globalData.onlineUrl+'/delOrderForWorkerById',
                  method: 'POST',
                  data: { orderProcessId: orderProcessId, workerId: workerId }
                });
              }
            }
            
            // 更新或添加工人
            for (const w of p.workers) {
              if (originalWorkerMap[w.workerId]) {
                // 更新现有工人，保留realNumber
                const originalWorker = originalWorkerMap[w.workerId];
                await this.wxRequest({
                  url: app.globalData.onlineUrl+'/upOrderForWorker',
                  method: 'POST',
                  data: {
                    id: originalWorker.id,
                    workerId: w.workerId,
                    workerName: w.workerName,
                    phone: w.phone,
                    workerprice: w.workerprice,
                    number: w.number,
                    realNumber: originalWorker.realNumber || 0
                  }
                });
              } else {
                // 添加新工人
                await this.wxRequest({
                  url: app.globalData.onlineUrl+'/addOrderForWorker',
                  method: 'POST',
                  data: {
                    orderProcessId: orderProcessId,
                    workerId: w.workerId,
                    workerName: w.workerName,
                    phone: w.phone,
                    workerprice: w.workerprice,
                    number: w.number,
                    realNumber: 0
                  }
                });
              }
            }
          } else {
            // 新工序：添加所有工人
            for (const w of p.workers) {
              await this.wxRequest({
                url: app.globalData.onlineUrl+'/addOrderForWorker',
                method: 'POST',
                data: {
                  orderProcessId: orderProcessId,
                  workerId: w.workerId,
                  workerName: w.workerName,
                  phone: w.phone,
                  workerprice: w.workerprice,
                  number: w.number,
                  realNumber: 0
                }
              });
            }
          }
          
          processIds.push(orderProcessId);
        }
        console.log('所有工序ID:', processIds);
        wx.request({
          url: app.globalData.onlineUrl+url,
          method: 'POST',
          data: {
            id:this.data.id,
            orderId:orderId,
            state:this.data.state,
            orderName:this.data.orderName, 
            customerId:this.data.customerId, 
            customerName:this.data.customerName, 
            remark:this.data.remark, 
          },
          success: (res) => {
            if (res.data.code === 1) {
              wx.showToast({
                title: '订单提交成功',
                icon: 'success'
              });
              wx.switchTab({
                url: '/pages/navigator/filter/index'
              });
              // 更新数据或跳转页面
              // this.setData({ processIds });
            } else {
              // 处理错误情况
              wx.showToast({
                title: res.data.msg || '订单提交失败',
                icon: 'none',
                duration: 3000
              });
            }
          },
          fail: (err) => {
            console.error('订单提交请求失败:', err);
            wx.showToast({
              title: '网络错误，请重试',
              icon: 'none',
              duration: 3000
            });
          }
        });
      } catch (error) {
        console.error('订单提交失败:', error);
        wx.showToast({
          title: `提交失败: ${error.message || '未知错误'}`,
          icon: 'none',
          duration: 3000
        });
      }
    }
  },
  validateOrderData(processArry) {
    const errors = [];
    let priceFlag=0;
    if (!processArry || !Array.isArray(processArry)) {
      errors.push('工序数据格式错误');
      return { isValid: false, errors ,priceFlag};
    }
    if (processArry.length === 0) {
      errors.push('至少需要添加一个工序');
    }
    // 3. 遍历验证每个工序
    processArry.forEach((process, index) => {
      const processPrefix = `工序 ${index + 1}: `;
      if (!process.processName?.trim()) {
        errors.push(`${processPrefix}工序不能为空`);
      }
      if (!process.unitName?.trim()) {
        errors.push(`${processPrefix}单位不能为空`);
      }
      if (!process.customerprice) {
        errors.push(`${processPrefix}客户价格不能为空`);
      } else if (isNaN(parseFloat(process.customerprice))) {
        errors.push(`${processPrefix}客户价格必须是有效数字`);
      }
      // 4. 验证工人数组
      if (!process.workers || !Array.isArray(process.workers)) {
        errors.push(`${processPrefix}工人数据格式错误`);
        return;
      }
      if (process.workers.length === 0) {
        errors.push(`${processPrefix}至少需要添加一个工人`);
      }
      // 5. 遍历验证每个工人
      process.workers.forEach((worker, workerIndex) => {
        const workerPrefix = `${processPrefix}工人 ${workerIndex + 1}: `;
        if (!worker.workerName?.trim()) {
          errors.push(`${workerPrefix}工人名称不能为空`);
        }
        if (!worker.workerprice) {
          errors.push(`${workerPrefix}工人价格不能为空`);
        } else if (isNaN(parseFloat(worker.workerprice))) {
          errors.push(`${workerPrefix}工人价格必须是有效数字`);
        }else if (parseFloat(worker.workerprice)>=process.customerprice) {
          errors.push(`${workerPrefix}工人单价必须小于客户单价`);
          priceFlag=1;
        }
        if (!worker.number) {
          errors.push(`${workerPrefix}加工数量不能为空`);
        } else if (isNaN(parseInt(worker.number)) || parseInt(worker.number) <= 0) {
          errors.push(`${workerPrefix}加工数量必须是大于0的整数`);
        }
      });
    });
    return {
      isValid: errors.length === 0,
      errors,
      priceFlag
    };
  },
  getCustomer(){
    let _this=this;
        wx.request({
          url: app.globalData.onlineUrl+'/getCustomer',
          method: 'POST',
          data: [],
          header: {'content-type': 'application/json' }, // 请求头
          success: function (res) {
            let data=res.data.data;
            _this.setData({
              customerList: data,
              currentData: data
            })
          },
          fail: function (err) {
          }
        }); 
  },
  getWorker(){
    let _this=this;
        wx.request({
          url: app.globalData.onlineUrl+'/getWorker',
          method: 'POST',
          data: [],
          header: {'content-type': 'application/json' }, // 请求头
          success: function (res) {
            let data=res.data.data;
            _this.setData({
              workerList: data,
              currentWorkerData:data
            })
          },
          fail: function (err) {
          }
        }); 
  },
  getProcess(){
    let _this=this;
        wx.request({
          url: app.globalData.onlineUrl+'/getProcesses',
          method: 'POST',
          data: [],
          header: {'content-type': 'application/json' }, // 请求头
          success: function (res) {
            let data=res.data.data;
            _this.setData({
              processList: data
            })
          },
          fail: function (err) {
          }
        }); 
  },
  getUnit(){
    let _this=this;
        wx.request({
          url: app.globalData.onlineUrl+'/getUnit',
          method: 'POST',
          data: [],
          header: {'content-type': 'application/json' }, // 请求头
          success: function (res) {
            let data=res.data.data;
            _this.setData({
              unitList: data
            })
          },
          fail: function (err) {
          }
        }); 
  },
  /**
   * 生命周期函数--监听页面加载
   */
onLoad: function (options) {
    this.getCustomer();
    this.getWorker();
    this.getUnit();
    this.getProcess();
    console.log(666,options.id);
    this.setData({
      id:options.id
    })
    if(options.id){
      try {
        this.loadFormData(options.id).then((res) => {
          res.processArry.forEach((obj, index) => {
            obj.unitIndex=this.data.unitList.findIndex(item => item.id == obj.unitId)
            obj.processIndex=this.data.processList.findIndex(item => item.id == obj.processId)
          });
          this.setData({
            orderId: res.orderId,
            orderName: res.orderName,
            customerIndex:this.data.customerList.findIndex(item => item.id == res.customerId),
            customerId: res.customerId,
            customerName: res.customerName,
            state:res.state,
            remark: res.remark,
            processArry:res.processArry
          })
        });
        
        
      } catch (error) {
        // 错误处理
      }
    }
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },
  async loadFormData(id) {
    try {
      // 1. 获取订单基础数据
      const orderResult = await this.wxRequest({
        url: app.globalData.onlineUrl+'/getOrderById',
        method: 'POST',
        data: { id: id }
      });
      const formData = {
        ...orderResult,
        processArry: []
      };
      console.log(123456,formData);
      // 2. 获取工序数据
      const processResult = await this.wxRequest({
        url: app.globalData.onlineUrl+'/getProcessByProcessIds',
        method: 'POST',
        data: { orderId:formData.orderId }
      });
      
      // 3. 获取每个工序的工人数据
      const processPromises = processResult.map(async process => {
        const workerResult = await this.wxRequest({
          url: app.globalData.onlineUrl+'/getWorkerByWorkerIds',
          method: 'POST',
          data: { orderProcessId:process.orderProcessId }
        });
        return {
          ...process,
          workers: workerResult
        };
      });
      // 4. 等待所有工序数据加载完成
      const processedData = await Promise.all(processPromises);
      formData.processArry = processedData;
      console.log('表单数据加载完成:', formData);
      return formData;
    } catch (error) {
      console.error('数据加载失败:', error);
      throw error;
    }
  },
  // 微信小程序请求封装（示例）
  wxRequest: function (options) {
    return new Promise((resolve, reject) => {
      wx.request({
        url: options.url,
        method: options.method || 'GET',
        data: options.data || {},
        header: {
          'Content-Type': 'application/json',
          'Authorization': 'Bearer ' + wx.getStorageSync('token')
        },
        success: (res) => {
          if (res.data.code == 1) {
            resolve(res.data.data);
          } else {
            reject(new Error(res.data.msg || `请求失败: ${res.data.code}`));
          }
        },
        fail: (err) => {
          console.error('网络请求失败:', err);
          reject(new Error('网络请求失败，请检查网络连接'));
        }
      });
    })
  },
  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  },
  getOrderNo: function(fmt){
    let date=new Date();
    var o = {
      "M+" : date.getMonth()+1,                 //月份
      "d+" : date.getDate(),                    //日
      "h+" : date.getHours(),                   //小时
      "m+" : date.getMinutes(),                 //分
      "s+" : date.getSeconds(),                 //秒
      "q+" : Math.floor((date.getMonth()+3)/3), //季度
      "S"  : date.getMilliseconds()             //毫秒
    };
  
    if(/(y+)/.test(fmt)){
      fmt=fmt.replace(RegExp.$1, (date.getFullYear()+"").substr(4 - RegExp.$1.length));
    }
          
    for(var k in o){
      if(new RegExp("("+ k +")").test(fmt)){
        fmt = fmt.replace(
          RegExp.$1, (RegExp.$1.length==1) ? (o[k]) : (("00"+ o[k]).substr((""+ o[k]).length)));  
      }       
    }
  
    return fmt;        
}
});
